package com.atguigu.flink.day06;

import com.atguigu.flink.beans.WaterSensor;
import com.atguigu.flink.func.WaterSensorMapFunction;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.datastream.WindowedStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

/**
 * @author Felix
 * @date 2023/12/6
 * 该案例演示了watermark的生成策略--单调递增
 */
public class Flink01_watermark_Monotonous {
    public static void main(String[] args) throws Exception {
        //指定流处理环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        //指定Watermark生成周期，默认200毫秒
        // env.getConfig().setAutoWatermarkInterval(200);
        env.setParallelism(1);

        //从指定网络端口读取数据
        SingleOutputStreamOperator<WaterSensor> wsDS = env
            .socketTextStream("hadoop102", 8888)
            .map(new WaterSensorMapFunction());

        //指定Watermark的生成策略  并提取事件时间字段
        SingleOutputStreamOperator<WaterSensor> withWatermarkDS = wsDS.assignTimestampsAndWatermarks(
            //Flink提供默认的两种水位线的生成策略：单调递增(有序)、有界乱序，都是周期性生成的
            WatermarkStrategy
                //指定生成策略为单调递增
                .<WaterSensor>forMonotonousTimestamps()
                .withTimestampAssigner(
                    new SerializableTimestampAssigner<WaterSensor>() {
                        //从流中数据中提取事件时间
                        @Override
                        public long extractTimestamp(WaterSensor ws, long recordTimestamp) {
                            return ws.getTs();
                        }
                    }
                )
        );

        //分组
        KeyedStream<WaterSensor, String> keyedDS = withWatermarkDS.keyBy(WaterSensor::getId);
        //开窗
        WindowedStream<WaterSensor, String, TimeWindow> windowDS
            = keyedDS.window(TumblingEventTimeWindows.of(Time.milliseconds(10)));
        //对窗口数据进行处理
        windowDS.process(
            new ProcessWindowFunction<WaterSensor, String, String, TimeWindow>() {
                @Override
                public void process(String s, Context context, Iterable<WaterSensor> elements, Collector<String> out) throws Exception {
                    long count = elements.spliterator().estimateSize();
                    String windowStart = DateFormatUtils.format(context.window().getStart(), "yyyy-MM-dd HH:mm:ss.SSS");
                    String windowEnd = DateFormatUtils.format(context.window().getEnd(), "yyyy-MM-dd HH:mm:ss.SSS");
                    out.collect("key=" + s + "的窗口[" + windowStart + "," + windowEnd + ")包含" + count + "条数据===>" + elements.toString());
                }
            }
        ).print("$$");

        env.execute();
    }
}
